package com.qf.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.dao.OrderMapper;
import com.qf.pojo.po.XcOrder;
import com.qf.pojo.resp.BaseResp;
import com.qf.service.PayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author lipengg
 * @date 2021/10/22
 */
@Service
public class PayServiceImpl implements PayService {

    @Autowired
    private OrderMapper orderMapper;

    protected Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);

    @Value("${pay.url}")
    private String url;
    @Value("${pay.APP_ID}")
    private String APP_ID;
    @Value("${pay.APP_PRIVATE_KEY}")
    private String APP_PRIVATE_KEY;
    @Value("${pay.ALIPAY_PUBLIC_KEY}")
    private String ALIPAY_PUBLIC_KEY;

    @Override
    @Transactional
    public BaseResp isPay(Map mapReq) {
//        System.out.println("url"+url);
        logger.info("map信息"+mapReq);
        //获得订单信息
        Object payOrder = mapReq.get("payOrder");
        String s1 = JSON.toJSONString(payOrder);
        //前端数据
        XcOrder xcOrder = JSONObject.parseObject(s1, XcOrder.class);
        //数据库数据
        XcOrder order = orderMapper.findById(xcOrder.getOrderId().toString());
        if (order == null){
            return new BaseResp(1,"支付错误",null,null);
        }
        logger.info("==============="+xcOrder.getOrderId()+"订单进入支付");
        //修改订单状态为正在支付   订单状态：1.未支付。2.已支付。3.正在支付。4.取消支付
        //前端传来的价格和数据库价格相符合才支付,否则失败
        if (!order.getOrderPay().toString().equals(xcOrder.getOrderPay().toString())){
            //
            return new BaseResp(1,"支付错误",null,null);
        }
        order.setOrderStatus(2);
        orderMapper.updateOrder(order);
        logger.info("修改订单为正在支付状态成功");
        //支付宝创建
        AlipayClient alipayClient =  new DefaultAlipayClient(url, APP_ID, APP_PRIVATE_KEY, "json", "utf-8", ALIPAY_PUBLIC_KEY, "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
        //同步返回的调用结果 ---》当用户支付成功后，通过跳转到是商户支付成功页面
        //https://www.domain.com/CallBack/return_url
        //内网穿透：1.将自己本地的ip 发布到公网上
        alipayRequest.setReturnUrl( "http://123.57.72.181/#/paySuccess");
        //异步返回的结果 ---》当用户支付成功后，支付宝通过post请求到了你的接口的地址，将支付的参数携带，并且用户进行验签
        alipayRequest.setNotifyUrl( "http://123.57.72.181:8082/xcOrderPay/notifyUrl"  ); //在公共参数中设置回跳和通知地址
        //使用FastJson进行转换
        Map map = new HashMap<>();
        // Map sysMap = new HashMap<>();
        //1。订单号
        map.put("out_trade_no",order.getOrderId());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",order.getOrderPay());
        map.put("subject","携程竭诚为您服务");
        map.put("body","携程业务订单");
        //转为Json结构
        String s = JSONObject.toJSONString(map);
        alipayRequest.setBizContent(s);
        String form= "" ;
        try  {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }

        return new BaseResp(0,"请求成功！",null,form);
    }

    @Override
    public BaseResp isReturnUrl(HttpServletRequest request) {
        logger.info("==============进入异步回调方法========");
        //利用工具方法将request请求转为Map
        Map<String, String> stringStringMap = convertRequestParamsToMap(request);
        boolean  signVerified = false;  //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(stringStringMap, ALIPAY_PUBLIC_KEY, "utf-8", "RSA2");
            if (signVerified){
                logger.info("=======验签成功=========");
                System.out.println(stringStringMap);
                if (stringStringMap.get("trade_status").equals("TRADE_SUCCESS")){
                    //支付成功
                    String out_trade_no = stringStringMap.get("out_trade_no");
                    //修改订单状态
                    XcOrder order = orderMapper.findById(out_trade_no);
                    order.setOrderStatus(3);
                    orderMapper.updateOrder(order);
                }
                return null;
            } else {
                logger.info("=======验签失败=========");
                // TODO 验签失败则记录异常日志，并在response中返回failure.
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 将request中的参数转换成Map
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<String, String>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

}
